package com.sx.admin.controller.plat;

import com.sx.admin.controller.BaseController;
import com.sx.admin.shiro.SecurityUserUtils;
import com.sx.core.CardConstants;
import com.sx.core.model.Information;
import com.sx.core.model.Operator;
import com.sx.core.mybatis.SessionTemplate;
import com.sx.core.utils.Md5;
import com.sx.core.utils.UUIDUtils;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.Params;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lihao on 2017/6/29.
 */
@RequestMapping("pl/operator")
@RestController
public class OperatorController extends BaseController {

    @Autowired
    SessionTemplate sessionTemplate;
    @RequestMapping("list")
    public JsonReaderResponse list(HttpServletRequest request){


        return new JsonReaderResponse(sessionTemplate.list(Operator.class));
    }
    @RequestMapping("save")
    public JsonReaderResponse list(Operator role, HttpServletRequest request){
        if(StringUtils.isEmpty(role.getId())){
            Operator exist = sessionTemplate.get(Operator.class,role.getOpercode());
            if(exist!=null){
                return new JsonReaderResponse("用户名已存在",101);
            }
            role.setId(UUIDUtils.generateUuid32());
            sessionTemplate.save(role);
        }else{
            sessionTemplate.edit(role);
        }
        return new JsonReaderResponse();
    }

    @RequestMapping("del")
    public JsonReaderResponse del(String opercode,HttpServletRequest request){
        sessionTemplate.delete(Operator.class,opercode);
        return new JsonReaderResponse();
    }
    @RequestMapping("changePwd")
    public JsonReaderResponse changePwd(String opercode,String password,String oldPasswd,HttpServletRequest request){
        if(StringUtils.isEmpty(opercode)){
            opercode= SecurityUserUtils.getOperator().getOpercode();

            String simpleHash = new SimpleHash(CardConstants.password_algorithmName, password, CardConstants.password_salt).toString();

            sessionTemplate.edit(Operator.class,"updatePwd",new Params().p("operpin",simpleHash).p("opercode",opercode));

        }else{
            sessionTemplate.edit(Information.class,"updatePwd",new Params().p("password", Md5.md5(password)).p("id",opercode));
        }
        return new JsonReaderResponse();
    }




}
